<?php
namespace App\Services;

use GuzzleHttp\Client;


class CloundPay
{

    private $appid;
    private $secretKey;

    function __construct()
    {
        $this->appid = config('cloundpay.app_id');
        $this->secretKey = config('cloundpay.secret_key');
        $this->notifyUrl = config('cloundpay.notify_url');
    }

    public function withdraw($data)
    {
        $withdraw = [
            'appid' => $this->appid,
            'channel' => $data['channel'],
            'order_no' => $data['order_no'],
            'amount' => $data['amount'],
            'description' => $data['description'],
        ];
        if ($withdraw['channel'] == 'ali') {
            $withdraw['recipient_account_type'] = 'ALIPAY_LOGONID';
            $withdraw['recipient_account'] = $data['recipient_account'];
            $withdraw['recipient_name'] = $data['recipient_name'];
        } else {
            $withdraw['recipient_card'] = $data['recipient_card'];
            $withdraw['recipient_bank_code'] = $data['recipient_bank_code'];
            $withdraw['recipient_name'] = $data['recipient_name'];
            $withdraw['url'] = $this->notifyUrl;
        }
        $withdraw['sign'] = $this->sign($withdraw, $this->secretKey);
        $client = new Client();
        $response = $client->request('POST', 'http://api.a0106.xyz/api/api/withdraw', [
            'form_params' => $withdraw
        ]);
        return $response->getBody()->getContents();
    }

    public function sign($data, $key)
    {
        $data = $this->argSort($data);
        $data = $this->createLinkstring($data);
        $sign = strtoupper(md5($data . '&key=' . $key));
        return $sign;
    }

    public function argSort($para)
    {
        ksort($para);
        reset($para);
        return $para;
    }


    public function createLinkstring($para)
    {

        $arg  = "";

        foreach ($para as $key => $val) {
            $arg .= $key . "=" . $val . "&";
        }

        $arg = substr($arg, 0, strlen($arg) - 1);

        if (get_magic_quotes_gpc()) {
            $arg = stripslashes($arg);
        }

        return $arg;
    }
}
